package com.alan.wc;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 流式处理
 * @author: Alan
 * @date: 2021/5/9 0:12
 */
public class StreamWordCount {

    public static void main(String[] args) throws Exception {
        // 创建流处理执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        env.setParallelism(1);

        // 从文件中读取数据
//        String filePath = "D:\\IT_ALAN\\gitee\\javaProject\\FlinkTutoral\\src\\main\\resources\\hello.txt";
//        DataStream<String> inputDataStream = env.readTextFile(filePath);

        // 用paramter tool工具从程序启动参数中提取配置项,在启动的Program args中添加"-host localhost -port 9999"
        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        String host = parameterTool.get("host");
        int port = parameterTool.getInt("port");

        // 从socker文本读取数据 在命令行下用 nc -lk 9999（linux）或nc -L -p 9999（windows下nc得自行下载） 来输入
//        DataStreamSource<String> inputDataStream = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> inputDataStream = env.socketTextStream(host, port);

        // 基于数据流进行转换计算
        DataStream<Tuple2<String, Integer>> resultStream = inputDataStream.flatMap(new MyFlaMapper())
                .keyBy(0)
                .sum(1);

        resultStream.print();

        // 执行任务
        env.execute();

    }

    /**
     * 自定义类，实现 FlatMapFunction 接口
     */
    private static class MyFlaMapper implements FlatMapFunction<String, Tuple2<String,Integer>> {

        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
            // 按空格分词
            String[] words = value.split(" ");
            // 遍历所有word，包成二元组输出
            for (String word:words) {
                out.collect(new Tuple2<String, Integer>(word,1));
            }
        }
    }
}
